package com.bwsoft.admin.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.dao.NewsCategoryDao;
import com.bwsoft.admin.domain.Account;
import com.bwsoft.admin.domain.NewsCategory;
import com.bwsoft.admin.domain.QualityControl;
import com.bwsoft.admin.domain.QualityControlJoiner;
import com.bwsoft.admin.domain.valueObject.QualityControlJoinerVO;
import com.bwsoft.admin.domain.valueObject.QualityControlVO;
import com.bwsoft.admin.service.QualityControlService;
import com.bwsoft.api.util.Constant;
import com.bwsoft.model.Message;
import com.bwsoft.service.DictionaryDataService;
import com.bwsoft.util.UploadFileUtil;

@Service(QualityControlService.NAME)
public class QualityControlServiceImpl extends BaseServiceImpl_ybd implements QualityControlService{
	private static Logger LOG = Logger.getLogger(QualityControlService.class.getClass());
	@Resource(name =  DictionaryDataService.NAME)
	DictionaryDataService dictionaryDataService;
	
	@Override
	public List<QualityControl> findData(Integer page, Integer rows, String s_qcId, String s_projectName, String s_sponsor, String s_status, String s_openFlag, String s_ptclsj, String s_ptxz) {
		StringBuffer qualityCtrlHql = new StringBuffer();
		Map<String, String> fieldMap=dictionaryDataService.getDicDataByName("qc_field");
		Map<String, String> statusMap=dictionaryDataService.getDicDataByName("qc_status");
		Map<String, String> scopeMap=dictionaryDataService.getDicDataByName("qc_scope");
		Map<String, String> countMap=dictionaryDataService.getDicDataByName("qc_count");
		Map<String, String> natureMap=dictionaryDataService.getDicDataByName("qc_nature");
		
		qualityCtrlHql.append("from QualityControl as ctrl where 1=1");
		if(s_qcId != null && !"".equals(s_qcId.trim())){
				qualityCtrlHql.append("and ctrl.qcId like '%"+s_qcId.trim()+"%'");
		}
		if(s_projectName != null && !"".equals(s_projectName.trim())){
			qualityCtrlHql.append("and ctrl.projectName like '%"+s_projectName.trim()+"%'");
		}
		if(s_sponsor != null && !"".equals(s_sponsor.trim())){
			qualityCtrlHql.append("and ctrl.sponsor.compName like '%"+s_sponsor.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			qualityCtrlHql.append("and ctrl.status = '"+s_status.trim()+"'");
		}
		if(s_openFlag != null && !"".equals(s_openFlag.trim())){
			qualityCtrlHql.append("and ctrl.openFlag = '"+s_openFlag.trim()+"'");
		}
		if(s_ptclsj != null && !"".equals(s_ptclsj.trim())){
			qualityCtrlHql.append("and ctrl.ptclsj = '"+s_ptclsj.trim()+"'");
		}
		if(s_ptxz != null && !"".equals(s_ptxz.trim())){
			qualityCtrlHql.append("and ctrl.ptxz = '"+s_ptxz.trim()+"'");
		}
		qualityCtrlHql.append(" order by ctrl.addTime desc");
		List<QualityControl> qualityControlData=qualityControlDao.findPage(qualityCtrlHql.toString(), rows, (page - 1) * rows);
	for (QualityControl qualityControl : qualityControlData) {
		if(qualityControl.getStatus()!=null)
			qualityControl.setStatusName(statusMap.containsKey(qualityControl.getStatus().toString())?statusMap.get(qualityControl.getStatus().toString()):"");
		if(qualityControl.getField()!=null)	
			qualityControl.setFieldName(fieldMap.containsKey(qualityControl.getField().toString())?fieldMap.get(qualityControl.getField().toString()):"");
		if(qualityControl.getScope()!=null)
			qualityControl.setScopeName(scopeMap.containsKey(qualityControl.getScope().toString())?scopeMap.get(qualityControl.getScope().toString()):"");
		if(qualityControl.getCount()!=null)
			qualityControl.setCountName(countMap.containsKey(qualityControl.getCount().toString())?countMap.get(qualityControl.getCount().toString()):"");
		if(qualityControl.getNature()!=null)
			qualityControl.setNatureName(natureMap.containsKey(qualityControl.getNature().toString())?natureMap.get(qualityControl.getNature().toString()):"");
		}
		return qualityControlData;
	}

	@Override
	public Long getTotalCount(String s_qcId, String s_projectName, String s_sponsor, String s_status, String s_openFlag, String s_ptclsj, String s_ptxz) {
		StringBuffer qualityCtrlHql = new StringBuffer();
		qualityCtrlHql.append("select count(*) from QualityControl as ctrl where 1=1");
		if(s_qcId != null && !"".equals(s_qcId.trim())){
				qualityCtrlHql.append("and ctrl.qcId like '%"+s_qcId.trim()+"%'");
		}
		if(s_projectName != null && !"".equals(s_projectName.trim())){
			qualityCtrlHql.append("and ctrl.projectName like '%"+s_projectName.trim()+"%'");
		}
		if(s_sponsor != null && !"".equals(s_sponsor.trim())){
			qualityCtrlHql.append("and ctrl.sponsor.compName like '%"+s_sponsor.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			qualityCtrlHql.append("and ctrl.status = '"+s_status.trim()+"'");
		}
		if(s_openFlag != null && !"".equals(s_openFlag.trim())){
			qualityCtrlHql.append("and ctrl.openFlag = '"+s_openFlag.trim()+"'");
		}
		if(s_ptclsj != null && !"".equals(s_ptclsj.trim())){
			qualityCtrlHql.append("and ctrl.ptclsj = '"+s_ptclsj.trim()+"'");
		}
		if(s_ptxz != null && !"".equals(s_ptxz.trim())){
			qualityCtrlHql.append("and ctrl.ptxz = '"+s_ptxz.trim()+"'");
		}
		Long count;
		count=(Long)qualityControlDao.findByHql(qualityCtrlHql.toString()).get(0);
		return count;
	}

	@Override
	public QualityControl findDataByID(int id) {
		Map<String, String> fieldMap=dictionaryDataService.getDicDataByName("qc_field");
		Map<String, String> statusMap=dictionaryDataService.getDicDataByName("qc_status");
		Map<String, String> scopeMap=dictionaryDataService.getDicDataByName("qc_scope");
		Map<String, String> countMap=dictionaryDataService.getDicDataByName("qc_count");
		Map<String, String> natureMap=dictionaryDataService.getDicDataByName("qc_nature");
		QualityControl qualityControl=qualityControlDao.findById(id);
		if(qualityControl.getImg1()!=null && qualityControl.getImg1().length()>1){
			qualityControl.setImg1(qualityControl.getImg1().substring(1));
		}
		if(qualityControl.getImg2()!=null && qualityControl.getImg2().length()>1){
			qualityControl.setImg2(qualityControl.getImg2().substring(1));
		}
		if(qualityControl.getImg3()!=null && qualityControl.getImg3().length()>1){
			qualityControl.setImg3(qualityControl.getImg3().substring(1));
		}
		if(qualityControl.getStatus()!=null)
			qualityControl.setStatusName(statusMap.containsKey(qualityControl.getStatus().toString())?statusMap.get(qualityControl.getStatus().toString()):"");
		if(qualityControl.getField()!=null)	
			qualityControl.setFieldName(fieldMap.containsKey(qualityControl.getField().toString())?fieldMap.get(qualityControl.getField().toString()):"");
		if(qualityControl.getScope()!=null)
			qualityControl.setScopeName(scopeMap.containsKey(qualityControl.getScope().toString())?scopeMap.get(qualityControl.getScope().toString()):"");
		if(qualityControl.getCount()!=null)
			qualityControl.setCountName(countMap.containsKey(qualityControl.getCount().toString())?countMap.get(qualityControl.getCount().toString()):"");
		if(qualityControl.getNature()!=null)
			qualityControl.setNatureName(natureMap.containsKey(qualityControl.getNature().toString())?natureMap.get(qualityControl.getNature().toString()):"");
		return qualityControl;
	}
	
	@Override
	public Account findSponsorDataByID(int id) {
		Map<String, String> typeMap=dictionaryDataService.getDicDataByName("account_type");
		Account account=accountDao.findById(id);
		if(account.getAccountType()!=null)
			account.setAccountTypeName(typeMap.containsKey(account.getAccountType().toString())?typeMap.get(account.getAccountType().toString()):"" );
		return account;
	}
	
	@Override
	public Message closeQualityControl(QualityControl qualityControl) {
		Message msg = new Message();
		try {
			QualityControl update_qcPojo = qualityControlDao.findById(qualityControl.getQcId());
			update_qcPojo.setOpenFlag(false);
			update_qcPojo.setCloseReason(qualityControl.getCloseReason());
			qualityControlDao.update(update_qcPojo);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}	
	
	@Override
	public Message openQualityControl(QualityControl qualityControl) {
		Message msg = new Message();
		try {
			qualityControl = qualityControlDao.findById(qualityControl.getQcId());
			qualityControl.setOpenFlag(true);
			qualityControl.setCloseReason("");
			qualityControlDao.update(qualityControl);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}	
	
	@Override
	public Message editQualityControl(QualityControl qualityControl) {
		Message msg = new Message();
		try {
			QualityControl update_qcPojo = qualityControlDao.findById(qualityControl.getQcId());
			update_qcPojo.setProjectName(qualityControl.getProjectName());
			update_qcPojo.setField(qualityControl.getField());
			update_qcPojo.setScope(qualityControl.getScope());
			update_qcPojo.setNature(qualityControl.getNature());
			update_qcPojo.setStandard(qualityControl.getStandard());
			update_qcPojo.setCount(qualityControl.getCount());
			update_qcPojo.setBeginDate(qualityControl.getBeginDate());
			update_qcPojo.setEndDate(qualityControl.getEndDate());
			update_qcPojo.setFeedBackDate(qualityControl.getFeedBackDate());
			update_qcPojo.setPrice(qualityControl.getPrice());
			update_qcPojo.setGbjgxx(qualityControl.getGbjgxx());
			update_qcPojo.setPtxz(qualityControl.getPtxz());
			update_qcPojo.setPtclsj(qualityControl.getPtclsj());
			update_qcPojo.setDescription(qualityControl.getDescription());
			update_qcPojo.setOther(qualityControl.getOther());
			qualityControlDao.update(update_qcPojo);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}	
	
	@Override
	public List<QualityControlJoiner> findJoinersData(Integer page, Integer rows, int qcId) {
		StringBuffer qualityCtrlJoinerHql = new StringBuffer();
		qualityCtrlJoinerHql.append("from QualityControlJoiner as joiners where 1=1");
		qualityCtrlJoinerHql.append("and joiners.qualityControl = '"+qcId+"'");
		qualityCtrlJoinerHql.append("order by addtime desc");
		List<QualityControlJoiner> qualityControlJoinerData=qualityControlDaoJoinerDao.findPage(qualityCtrlJoinerHql.toString(), rows, (page - 1) * rows);
		return qualityControlJoinerData;
	}

	@Override
	public int getJoinersTotalCount(int id) {
		int count=0;
		
		StringBuffer qualityCtrlJoinerHql = new StringBuffer();
		qualityCtrlJoinerHql.append("from QualityControlJoiner as joiners where 1=1");
		qualityCtrlJoinerHql.append("and joiners.qualityControl = '"+id+"'");
		qualityCtrlJoinerHql.append("order by addtime desc");
		List<QualityControlJoiner> qualityControlJoinerData=qualityControlDaoJoinerDao.findByHql(qualityCtrlJoinerHql.toString());
		count=qualityControlJoinerData.size();
		return count;
	}
	
	
	@Override
	public Message updateFile(QualityControl qualityControl, File file, String fileName) {
		Message msg = new Message();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			QualityControl update_qcPojo = qualityControlDao.findById(qualityControl.getQcId());
			
			if(file != null && !"".equals(file)){
				Calendar now = Calendar.getInstance();
				String pdfFilepath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_PDF_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String pdfFileName=null ;
				pdfFileName=UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf('.'), fileName.length());
				UploadFileUtil.uploadOneFile(pdfFileName, file, pdfFilepath);
				filePojo.setPath(Constant.PATH_PDF_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+pdfFileName);
				filePojo.setName(fileName);
				filePojo.setSize(String.valueOf(file.length()));
				filePojo.setAddTime(new Date());
				update_qcPojo.setFile(filePojo);
				update_qcPojo.setStatus(4);
				update_qcPojo.setReportStatus(true);
				if(fileName.lastIndexOf(".pdf") >= 0){
					update_qcPojo.setReportName(fileName.substring(0, fileName.lastIndexOf(".pdf")));
				}else if(fileName.lastIndexOf(".PDF") >= 0){
					update_qcPojo.setReportName(fileName.substring(0, fileName.lastIndexOf(".PDF")));
				}else{
					update_qcPojo.setReportName(fileName);
				}
			}
			
			qualityControlDao.update(update_qcPojo);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public List<QualityControlVO> getVo(List<QualityControl> qcs) {
		List<QualityControlVO> qclistVo = new ArrayList<QualityControlVO>();
		QualityControlVO qcVo = new QualityControlVO();
		for (QualityControl qc : qcs) {
			qcVo = new QualityControlVO();
			qcVo.setAddTime(qc.getAddTime());
			qcVo.setBeginDate(qc.getBeginDate());
			qcVo.setCloseReason(qc.getCloseReason());
			qcVo.setCountName(qc.getCountName());
			qcVo.setDescription(qc.getDescription());
			qcVo.setEndDate(qc.getEndDate());
			qcVo.setFeedBackDate(qc.getFeedBackDate());
			qcVo.setFieldName(qc.getFieldName());
			if(qc.getFile() != null && !"".equals(qc.getFile())){
				qcVo.setFileId(qc.getFile().getId().toString());
				qcVo.setFileName(qc.getFile().getName());
				qcVo.setFilePath(qc.getFile().getPath());
				qcVo.setFileSize(qc.getFile().getSize());
			}
			qcVo.setGbjgxx(qc.getGbjgxx());
			qcVo.setImg1(qc.getImg1());
			qcVo.setImg2(qc.getImg2());
			qcVo.setImg3(qc.getImg3());
			qcVo.setNatureName(qc.getNatureName());
			qcVo.setOpenFlag(qc.getOpenFlag());
			qcVo.setOther(qc.getOther());
			qcVo.setPrice(qc.getPrice());
			qcVo.setProjectName(qc.getProjectName());
			qcVo.setPtclsj(qc.getPtclsj());
			qcVo.setPtxz(qc.getPtxz());
			qcVo.setQcId(qc.getQcId());
			qcVo.setReportName(qc.getReportName());
			qcVo.setReportStatus(qc.getReportStatus());
			qcVo.setScopeName(qc.getScopeName());
			if(qc.getSponsor() != null && !"".equals(qc.getSponsor())){
				qcVo.setSponsorCompName(qc.getSponsor().getCompName());
				qcVo.setSponsorEmail(qc.getSponsor().getEmail());
				qcVo.setSponsorFax(qc.getSponsor().getFax());
				qcVo.setSponsorId(qc.getSponsor().getAccountId());
				qcVo.setSponsorLinkMan(qc.getSponsor().getLinkMan());
				qcVo.setSponsorPhone(qc.getSponsor().getPhone());
			}
			qcVo.setStandard(qc.getStandard());
			qcVo.setStatusName(qc.getStatusName());
			
			qcVo.setField(qc.getField());
			qcVo.setScope(qc.getScope());
			qcVo.setCount(qc.getCount());
			qcVo.setNature(qc.getNature());
			qcVo.setStatus(qc.getStatus());
			qcVo.setQualityControlJoinersLength(qc.getQualityControlJoiners().size());
			qclistVo.add(qcVo);
		}
		return qclistVo;
	}

	@Override
	public List<QualityControlJoinerVO> getJoinerVo(
			List<QualityControlJoiner> qcjs) {
		List<QualityControlJoinerVO> qcJoinerListVo = new ArrayList<QualityControlJoinerVO>();
		QualityControlJoinerVO qcJoinerVo = new QualityControlJoinerVO();
		for (QualityControlJoiner qcj : qcjs) {
			qcJoinerVo = new QualityControlJoinerVO();
			qcJoinerVo.setAddTime(qcj.getAddTime());
			qcJoinerVo.setId(qcj.getId());
			if(qcj.getJoinerId() != null && !"".equals(qcj.getJoinerId())){
				qcJoinerVo.setJoinerIdCompName(qcj.getJoinerId().getCompName());
				qcJoinerVo.setJoinerIdEmail(qcj.getJoinerId().getEmail());
				qcJoinerVo.setJoinerIdFax(qcj.getJoinerId().getFax());
				qcJoinerVo.setJoinerIdLinkMan(qcj.getJoinerId().getLinkMan());
				qcJoinerVo.setJoinerIdPhone(qcj.getJoinerId().getPhone());
				qcJoinerVo.setJoinerAddress(qcj.getJoinerId().getAddress());
			}
			qcJoinerListVo.add(qcJoinerVo);
		}
		
		return qcJoinerListVo;
	}

	@Override
	public Message remove(QualityControl qualityControl) {
		Message msg = new Message();
		try {
			StringBuffer qcHql = new StringBuffer();
			qcHql.append("delete from QualityControl as ctrl where ctrl.qcId ="+qualityControl.getQcId()); 
			qualityControlDao.executeByHql(qcHql.toString());
			
			StringBuffer qcjHql = new StringBuffer();
			qcjHql.append("delete from QualityControlJoiner as joiner where joiner.qualityControl.qcId ="+qualityControl.getQcId());
			qualityControlDaoJoinerDao.executeByHql(qcjHql.toString());
			
			msg.setMsgFlag(true);
			msg.setMsgStr("删除成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("删除失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}
	
}
